#include "../Header Files/CObjectManager.h"
#include "../../Renderer/Header Files/CRenderer_AL.h"

CObjectManager::CObjectManager()
{
}
CObjectManager::~CObjectManager()
{
	for (unsigned int i(0); i < m_vObjects.size(); ++i)
	{
		delete m_vObjects[i];
		m_vObjects[i] = NULL;
	}
}
CObjectManager* CObjectManager::GetInstance()
{
	static CObjectManager _cInstance;
	return &_cInstance;
}
void CObjectManager::Initialize()
{
	m_pRenderer = CRenderer_AL::GetInstance();
}
void CObjectManager::Shutdown()
{
	for (unsigned int i(0); i < m_vObjects.size(); ++i)
	{
		m_vObjects[i]->DestroyObject();
		m_vObjects.erase(m_vObjects.begin() + i);
		i = i - 1;
	}
}
void CObjectManager::Update(float fDT, cCamera_AL* _camera)
{
	for (unsigned int i = 0; i < m_vObjects.size(); ++i)
	{
		if (m_vObjects[i]->GetIfToBeRemoved() == true)
		{
			m_vObjects[i]->DestroyObject();
			m_vObjects.erase(m_vObjects.begin() + i);
			i = i - 1; 
		}
	}

	for (unsigned int i = 0; i < m_vObjects.size(); ++i)
	{
		m_vObjects[i]->Update(fDT);
		m_vObjects[i]->GetRenderNode()->SetPosition(m_vObjects[i]->GetPosition());
		m_pRenderNodes.push_back(m_vObjects[i]->GetRenderNode());
	}

	if ( _camera )
		m_pRenderer->Render(&m_pRenderNodes, _camera);
	m_pRenderNodes.clear();
}


void CObjectManager::RemoveObject(int _nID)
{
	if ((unsigned)_nID < m_vObjects.size() && _nID > 0)
		m_vObjects.erase(m_vObjects.begin() + _nID, m_vObjects.begin() + _nID);
}

void CObjectManager::RemoveObject(CBaseObject* _pObj)
{
	for (unsigned int i(0); i < m_vObjects.size(); ++i)
	{
		if (m_vObjects[i] == _pObj)
		{
			m_vObjects.erase(m_vObjects.begin() + i, m_vObjects.begin() + i);
			return;
		}
	}
}

CBaseObject* CObjectManager::GetBaseObject(int _nID)
{
	if ((unsigned)_nID < m_vObjects.size() && _nID > 0)
		return m_vObjects[_nID];
	return NULL;
}